import React, { Component } from 'react';
import { EditorState, convertToRaw, ContentState } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';

import { IMG_UPLOAD_URL, IMG_URL } from '../../../../api';

import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';


export default class RichTextEditor extends Component {

    constructor(props) {
        super(props);
        const { product } = this.props;

        if (product && product.detail) {
            const html = product.detail;
            const contentBlock = htmlToDraft(html);
            if (contentBlock) {
                const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
                const editorState = EditorState.createWithContent(contentState);
                this.state = { editorState };
            }
        } else {
            this.state = { editorState: EditorState.createEmpty() };
        }
    }

    onEditorStateChange = (editorState) => {
        this.setState({
            editorState
        });
    };

    getDetail() {
        return draftToHtml(convertToRaw(this.state.editorState.getCurrentContent()));
    }

    uploadIMG(file) {
        return new Promise(async (resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.open('POST', IMG_UPLOAD_URL);
            const data = new FormData()
            data.append('image', file);
            xhr.send(data);
            xhr.addEventListener('load', () => {
                const res = JSON.parse(xhr.responseText);
                const { url } = res.data;

                const link = IMG_URL + url.substring(url.lastIndexOf('/') + 1);

                resolve({data: {link}});
            })
            xhr.addEventListener('error', () => {
                const error = JSON.parse(xhr.responseText);
                reject(error);
            })
        })
    }

    render() {
        const { editorState } = this.state;
        return (
            <Editor
                editorState={editorState}
                wrapperClassName="demo-wrapper"
                wrapperStyle={{ border: '1px solid #eee', width: '980px' }}
                editorClassName="demo-editor"
                editorStyle={{ padding: '0 10px', width: '980px' }}
                onEditorStateChange={this.onEditorStateChange}
                toolbar={{
                    image: {
                        uploadCallback: this.uploadIMG,
                        alt: {
                            present: true,
                            mandatory: true
                        }
                    }
                }}
            />

        );
    }
}
